package com.heima.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.client.article.IArticleClient;
import com.heima.client.wemedia.IWemediaClient;
import com.heima.common.exception.CustomException;
import com.heima.common.redis.CacheService;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.dtos.UserRelationDto;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.pojos.user.ApUserFan;
import com.heima.model.common.pojos.user.ApUserFollow;
import com.heima.model.common.pojos.wemedia.WmUser;
import com.heima.user.mapper.ApUserFanMapper;
import com.heima.user.mapper.ApUserFollowMapper;
import com.heima.user.service.UserFollowService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserFollowServiceImpl implements UserFollowService {

    @Autowired
    private CacheService cacheService;
    @Autowired
    private IArticleClient apArticleClient;
    @Autowired
    private ApUserFollowMapper apUserFollowMapper;
    @Autowired
    private ApUserFanMapper apUserFanMapper;
    @Autowired
    private IWemediaClient wemediaClient;

    //关注
    private static final String FOLLOW_BEHAVIOR = "follow";
    private static final String FANS_BEHAVIOR = "fans";

    /**
     * 用户关注
     *
     * @param relationDto
     * @return
     */
    @Override
    public ResponseResult userFollow(UserRelationDto relationDto, String userId) {
        //1. 参数校验
        if (relationDto == null || relationDto.getArticleId() == null || relationDto.getAuthorId() == null) {
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }

        // 构建参数：用户id，关注作者id，粉丝昵称，创建时间
        //关注度：0：偶尔感兴趣 1：一般 2：经常 3：高度
        //是否动态通知：默认开启 0: 否, 1: 是

        //2. 查询ApUserFollow是否有数据
        ApUserFollow apUserFollow = apUserFollowMapper.selectOne(Wrappers.<ApUserFollow>lambdaQuery().
                eq(ApUserFollow::getUserId, userId).
                eq(ApUserFollow::getFollowId, relationDto.getAuthorId()));

        ApUserFan apUserFan = new ApUserFan();

        if (apUserFollow == null) {
            apUserFollow = new ApUserFollow();
            //添加用户关注信息表数据
            WmUser article = wemediaClient.getWmUserById(Long.valueOf(relationDto.getAuthorId()));
            //当前用户id
            apUserFollow.setUserId(Integer.valueOf(userId));
            apUserFollow.setFollowId(relationDto.getAuthorId());
            apUserFollow.setFollowName(article.getNickname());
            apUserFollow.setLevel((byte) 1); // 默认关注度设为一般
            apUserFollow.setIsNotice((byte) 1); // 默认开启动态通知
            apUserFollow.setCreatedTime(LocalDateTime.now());
            apUserFollowMapper.insert(apUserFollow);
            // 缓存更新
            cacheService.hPut(FOLLOW_BEHAVIOR, apUserFollow.getUserId() + "_" + apUserFollow.getFollowId(), JSON.toJSONString(apUserFollow));

            //添加用户粉丝信息表数据
            // 查询ApUserFan表以确定是否需要插入新记录
            apUserFan = apUserFanMapper.selectOne(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, relationDto.getAuthorId())
                    .eq(ApUserFan::getFansId, userId));

            if (apUserFan == null) {
                // 添加用户粉丝信息表数据
                apUserFan = new ApUserFan();
                apUserFan.setFansId(apUserFollow.getUserId());
                apUserFan.setFansName(apUserFollow.getFollowName());
                apUserFan.setUserId(relationDto.getAuthorId());
                apUserFan.setLevel((byte) 0); // 默认粉丝忠实度设为正常
                apUserFan.setIsDisplay((byte) 1); // 默认显示动态
                apUserFan.setIsShieldLetter((byte) 0); // 默认不屏蔽私信
                apUserFan.setIsShieldComment((byte) 0); // 默认不屏蔽评论
                apUserFan.setCreatedTime(LocalDateTime.now());
                apUserFanMapper.insert(apUserFan);
            }
        } else if (relationDto.getOperation() == 1) { //取消关注
            // 删除follow表数据
            apUserFollowMapper.deleteById(apUserFollow.getId());
            // 删除fan表数据
            apUserFanMapper.delete(Wrappers.<ApUserFan>lambdaQuery()
                    .eq(ApUserFan::getUserId, relationDto.getAuthorId())
                    .eq(ApUserFan::getFansId, userId));
            // 清除缓存中的关注关系
            cacheService.removeHashField(FOLLOW_BEHAVIOR, apUserFollow.getUserId() + "_" + apUserFollow.getFollowId());
        }

        // 6. 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }
}
